package com.snimay.app.menu;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.google.gson.Gson;
import com.snimay.app.menu.repository.MenuRepository;
import com.snimay.app.menu.vo.Menu;
import com.snimay.common.RestServiceController;
import com.snimay.util.ToWeb;
/**   
 * @Title      : MenuController.java
 * @Package    : com.snimay.app.menu
 * @Description: TODO 
 * @author     : xxy
 * @date       : 2018年5月7日 下午4:24:48
 * @version    : V1.0   
 */
@RestController
@RequestMapping("menu")
public class MenuController implements RestServiceController<Menu, Long>{
	@Autowired
	MenuRepository repository;
	@Override
	@GetMapping("/")
	public Object getOne(Long id) {
		ToWeb toweb = new ToWeb();
		toweb.setObjData(repository.findOne(id));
		return new Gson().toJson(toweb);
	}

	@GetMapping("/{name}")
	public Object getList() {
		ToWeb toweb = new ToWeb();
		toweb.setObjData(repository.findAll());
		return new Gson().toJson(toweb);
	}


	@Override
	@PostMapping 
	public Object postOne(@RequestBody Menu entity) {
		Menu pe = entity.parent;
		entity.parent=null;
		entity = repository.save(entity);
		if(pe!=null&&pe.id!=null&&pe.id>0) {
			pe  = repository.findOne(pe.id);
			entity.parent = pe;
			entity = repository.save(entity);
		}
		ToWeb toweb = new ToWeb();
		toweb.setObjData(entity);
		return new Gson().toJson(toweb);
	}

 
	@Override
	@PutMapping 
	public Object putOne(Long id,@RequestBody Menu entity) {
		Menu pe = entity.parent;
		entity.parent=null;
		if(pe!=null&&pe.id!=null&&pe.id>0) {
			pe  = repository.findOne(pe.id);
			entity.parent = pe;
		} 
		repository.save(entity);
		ToWeb toweb = new ToWeb();
		toweb.setObjData(entity);
		return new Gson().toJson(toweb);
	}

	
	@Override
	@DeleteMapping("/{id}")
	public Object deleteOne(@PathVariable("id") Long id) {
		ToWeb toweb = new ToWeb();
		repository.delete(id);
		return new Gson().toJson(toweb);
	}

	@Override
	public Object getList(Integer rowSize, Integer page) {
		// TODO Auto-generated method stub
		return null;
	}

 
	@Override
	public Object patchOne(Long id, Menu entity) {
		// TODO Auto-generated method stub
		return null;
	}

}
